<template>
  <!-- 门诊医生-处置 -->
  <a-card class="flex flex-col h-full">
    <div class="flex justify-between items-center my-2">
      <div class="flex items-center">
        <div class="flex-center"><span class="mx-2">显示已作废医嘱</span><a-switch v-model:checked="showCancel" /></div>
        <a-form-item class="ml-6 !mb-0" required>
          <template #label>代开医生：</template>
          <SelectTable v-model:value="opticianDoctor.empName" type="视光医生" placeholder="请选择" @select="onSelectDoctor" />
        </a-form-item>
        <a-form-item class="ml-6 !mb-0">
          <template #label>开具人：</template>
          {{ empName }}
        </a-form-item>
      </div>
      <div>
        <a-button type="primary" class="mr-2" @click="saveSign()">签署</a-button>
        <a-button class="mr-2" type="primary" ghost @click="templateModalOpen = true">处置套餐</a-button>
        <a-button @click="onPrint">打印处置单</a-button>
      </div>
    </div>
    <BaseTable
      max-fill
      :loading="loading"
      :data-source="dataSource"
      :scroll="{ x: 2000 }"
      column-code="00001133"
      :extra-height="64"
      :pagination="false"
      :row-class-name="getRowClass"
    >
      <template #bodyCell="{ column, index, record }">
        <template v-if="column.dataIndex === 'yzzt'">
          <a-tag v-if="record.yzzt === 0" color="blue">新开立</a-tag>
          <a-tag v-if="record.yzzt === 1" color="green">已签署</a-tag>
          <a-tag v-if="record.yzzt === 2" color="red">已作废</a-tag>
        </template>
        <template v-if="column.dataIndex === 'mc'">
          <EditCell title="处置类型" :disabled="record.yzzt === 1">
            <SelectMedicine
              v-model:value="record.sfxm"
              :insure-status="record?.insureStatus"
              type="处置"
              :search-params="{ xmlbList: [0, 3] }"
              :auto-focus="record.isNew && index > 0 && !record.isSuit"
              @select="onSelect($event, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'sl'">
          <EditCell title="次数">
            <BaseInput
              v-model:value="record.sl"
              v-input:int
              v-input-selection
              :auto-focus="record.isNew && focusCell === record.key + '次数'"
              placeholder="请输入"
              :suffix="record.sfxm?.dw"
              @keydown.enter="saveNewRows(true)"
              @change="onCalc(record)"
              @blur="editRow(record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'yssm'">
          <EditCell title="处置说明">
            <a-input v-model:value="record.yssm" v-input-selection placeholder="请输入" @blur="editRow(record)" />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'jfzt'">
          <a-tag v-if="record.jfzt === 0" color="blue">未收费</a-tag>
          <a-tag v-if="record.jfzt === 1" color="green">已收费</a-tag>
        </template>
        <template v-if="column.dataIndex === 'zxzt'">
          <a-tag v-if="record.zxzt === 0" color="blue">未执行</a-tag>
          <a-tag v-if="record.zxzt === 1" color="green">已执行</a-tag>
        </template>
        <template v-if="column.dataIndex === 'orderType'">
          {{ record.orderType === 2 ? '套餐' : '单项' }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <BaseButton v-if="record.yzzt === 1 && record.jfzt === 0" danger type="text" size="small" confirm-text="撤销签署?" @click="saveSign(record.id)">
            撤销
          </BaseButton>
          <BaseButton confirm-text="确认作废？" type="link" size="small" :disabled="record.zxzt === 1" danger @click="onDelete(record)">作废</BaseButton>
          <a-button v-if="record?.insureStatus === 1" size="small" danger type="text" @click="onClickFunded(record, 2)">强制自费</a-button>
          <BaseButton v-if="record?.insureStatus === 2" confirm-text="撤销自费？" danger size="small" type="text" @click="onClickFunded(record, 1)"
            >撤销自费</BaseButton
          >
        </template>
      </template>
      <template #footer>
        <div class="sticky bottom-0 flex justify-between pl-20 items-center">
          <div class="text-center flex-1">
            <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :icon="h(SaveOutlined)" :disabled="!isHaveNewRow && !isDoctorChange" @click="saveNewRows()"> 保存 </a-button>
          </div>
          <div class="text-right w-80 pr-6 font-semibold text-base">
            <template v-if="!isArmy">
              <span>待缴费 ￥{{ chargePrice.notChargedAmount }}</span>
              <span class="ml-4">总费用 ￥{{ chargePrice.amount }}</span>
            </template>
          </div>
        </div>
      </template>
    </BaseTable>
    <TemplateModal v-model:open="templateModalOpen" @success="onAddTemplate" />
  </a-card>
</template>
<script setup>
import { ref, computed, watchEffect, h } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { intersection } from 'lodash-es'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import useStore from '../store'
import TemplateModal from './TemplateModal'

const { empName } = useUserStore()
const store = useStore()
const templateModalOpen = ref(false)
const loading = ref(false)
const focusCell = ref(null)
const opticianDoctor = ref({})
const dataSource = ref([])
const tableListId = ref([])
const showCancel = ref(false)
const signState = ref()
const isEmpty = ref(true)
// const selectKey = ref(Math.random())
const defaultRow = { isNew: true, cfbh: 1, yzzt: 0 }
const isHaveNewRow = computed(() => {
  return dataSource.value.some((item) => item.isNew)
})
//删除空行
const onDeleteEmptyRow = () => {
  dataSource.value = dataSource.value.filter((item) => item.sfxm?.mc)
}
const saveNewRows = async (addNew) => {
  onDeleteEmptyRow()
  dataSource.value.forEach((item) => {
    if (!item.sfxm || !item.sl) {
      message.destroy()
      isEmpty.value = false
      return message.error('请填写完整信息')
    } else {
      isEmpty.value = true
    }
  })
  isEmpty.value && fetchSave(addNew)
  // const newRows = dataSource.value.filter((item) => item.isNew)
  // newRows.forEach((item) => {
  //   fetchSave(item, addNew)
  // })
}
const editRow = (row) => {
  if (row.yzzt === 1) {
    message.error('已签署不可修改')
    getData()
  } else {
    !row.isNew && saveNewRows()
  }
}
const fetchSave = async (addNew = false) => {
  // 去除已作废的
  const newList = dataSource.value.filter((i) => {
    return i.yzzt !== 2
  })
  if (!opticianDoctor.value.empId) {
    return message.error('请选择代开医生')
  }
  const newRows = newList.map((row) => {
    return {
      jzbh: store.currentPatient.jzbh, //编号
      ysbh: opticianDoctor.value.empId,
      ...row,
      type: 'SG'
    }
  })
  const { code, msg } = await post('/outp/mzys/doSaveOutpClinicalOrderInfoList', newRows)
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('保存成功')
  await getData(addNew)
}

// 签署
const saveSign = async (id = '') => {
  if (!tableListId.value.length) {
    return message.error('不能为空')
  }
  id ? (signState.value = 0) : (signState.value = 1)
  const { code, msg } = await post('/outp/mzys/signedDoctor', {
    yzid: id ? [id] : tableListId.value,
    yzzt: signState.value
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}

//获取数据
const getData = async (addNew) => {
  loading.value = true
  const { data, code } = await post('/outp/mzys/getPatientTreatmentInfoList', {
    jzbh: store.currentPatient.jzbh, //就诊编号
    czsfck: showCancel.value ? 1 : 0,
    type: 'SG'
  })
  loading.value = false
  if (code !== 0) return
  if (data.length > 0) {
    dataSource.value = data.map((item) => {
      return { ...item, key: item.id }
    })
    opticianDoctor.value.empId = data[data.length - 1].ysbh
    opticianDoctor.value.empName = data[data.length - 1].xdys
    addNew && addRow()
  } else {
    dataSource.value = [{ key: 'row-0', ...defaultRow }]
  }
  tableListId.value = []
  dataSource.value.forEach((i) => {
    if (i.id) {
      tableListId.value.push(i.id)
    }
  })
  getTotal()
}
const chargePrice = ref({})
const getTotal = async () => {
  const { data, code } = await post('/outp/outpClinicalOrder/getOutpClinicalOrderAmount', {
    jzbh: store.currentPatient.jzbh, //就诊编号
    yzlb: [],
    iscz: '1',
    type: 'SG'
  })
  if (code !== 0) return
  chargePrice.value = {
    amount: data?.amount || '0.00',
    notChargedAmount: data?.notChargedAmount || '0.00'
  }
}

watchEffect(() => store.currentPatient.jzbh && getData())

const onAddTemplate = (list) => {
  //判断处方中是否有重复项目
  const currentTableYPBHS = dataSource.value.map((item) => item.sfxm?.bh)
  const templateYPBHS = list.map((item) => {
    item.zje = item.sl * item.dj
    item.yzzt = 0
    return item.bh
  })
  const repeatIds = intersection(currentTableYPBHS, templateYPBHS)
  if (repeatIds.length > 0) {
    const itemName = dataSource.value.find((item) => item.sfxm?.bh === repeatIds[0]).mc
    return message.error(`已有项目【${itemName}】，请勿重复添加`)
  }
  templateModalOpen.value = false
  onDeleteEmptyRow()
  dataSource.value = [...dataSource.value, ...list]
}
const getRowClass = (record) => {
  const className = {
    'table-row-suit': record.isSuit,
    'table-row-new': record.isNew,
    'table-row-disabled': record.yzzt === 2
  }
  return Object.keys(className)
    .filter((key) => className[key])
    .join(' ')
}
const onSelect = (selected, record) => {
  record.lbmc = selected.lbmc
  record.mc = selected.mc
  record.sfxm = selected
  record.sl = 1
  record.dj = selected.dj || 0
  record.zje = record.sl * record.dj
  record.dw = selected.dw
  focusCell.value = record.key + '次数'
  editRow(record)
}
// 自费
const onClickFunded = async (row, state) => {
  const { code, msg } = await post('/outp/mzys/doCompulsorySelfpaymentInfo', {
    insureStatus: state,
    yzbh: row.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}
const onDelete = async (row) => {
  if (row.isNew) {
    if (row.isSuit) {
      dataSource.value = dataSource.value.filter((item) => item.tcid !== row.tcid)
    } else {
      const index = dataSource.value.findIndex((item) => item.key === row.key)
      dataSource.value.splice(index, 1)
    }
    message.success('删除成功')
  } else {
    const { code } = await post('/outp/mzys/doDelOutpClinicalOrderInfo', { yzbh: row.id })
    if (code !== 0) return message.error('删除失败')
    message.success('删除成功')
    getData()
  }
}
const addRow = () => {
  const key = `row-${Math.random().toString().slice(2)}`
  dataSource.value.push({ key, ...defaultRow })
}

const onPrint = async () => {
  const { code, msg, data } = await post('/outp/outPrint/getTreatmentSheet', { mzjlbh: store.currentPatient.jzbh, pjhm: store.currentPatient.pjhm })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const onCalc = (row) => {
  row.zje = row.sl * row.dj
}
const isDoctorChange = ref(false)
const onSelectDoctor = (row) => {
  opticianDoctor.value = row
  isDoctorChange.value = true
}
</script>
<style lang="less" scoped></style>
